<?php
/**
 * Created by PhpStorm.
 * User: 李大爷
 * Date: 2019/3/5
 * Time: 14:05
 */

namespace app\controllers;

use Yii;
use yii\db\Query;
use yii\data\Pagination;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\NotFoundHttpException;
class CdrController extends BaseController
{
    /**
     * 通话记录列表
     * @return string|\yii\web\Response
     * @throws \yii\base\InvalidConfigException
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isAjax){
            //搜索条件
            $where = ['and'];
            $calltime = Yii::$app->request->get('calltime');
            if ($calltime){
                $explode = explode(' - ',$calltime);
                array_push($where,['between','calltime',trim($explode[0]),trim($explode[1])]);
            }
            $src = Yii::$app->request->get('src');
            if ($src){
                array_push($where,'src='.$src);
            }
            $dst = Yii::$app->request->get('dst');
            if ($dst){
                array_push($where,'dst='.$dst);
            }
            //切换到cdr数据库

            $db = (new Query())->from('dgg_cdr')->where($where);
            $count = $db->count('*');
            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $db->orderBy('id desc')->offset(($page-1)*$limit)->limit($limit)->all();
            foreach ($data as &$d){
                //$d['disposition_name'] = Yii::$app->params['cdr_disposition'][$d['disposition']];
                $d['play_url'] = Url::to(['play','uniqueid'=>$d['uniqueid']]);
                $d['download_url'] = Url::to(['download','uniqueid'=>$d['uniqueid']]);
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data,
            ]);
        }
        return $this->render('index');
    }

    /**
     * 删除通话记录
     * @return \yii\web\Response
     * @throws \yii\base\InvalidConfigException
     */
    public function actionDestroy()
    {
        $ids = Yii::$app->request->post('ids');
        //切换到cdr数据库
        $cdr_db = Yii::$app->get('db');
        $transaction = $cdr_db->beginTransaction();
        try{
            $cdr_db->createCommand()->delete('dgg_cdr',[
                'uniqueid' => $ids
            ])->execute();
            $transaction->commit();
            return $this->asJson(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            $transaction->rollBack();
            return $this->asJson(['code'=>1,'msg'=>'删除失败','data'=>$exception->getMessage()]);
        }
    }

    /**
     * 录音下载
     * @param $uniqueid
     * @return bool|string
     * @throws NotFoundHttpException
     */
    public function actionDownload($uniqueid)
    {
        $cdr = (new Query())->from('dgg_cdr')->where(['uniqueid'=>$uniqueid])->one();
        if ($cdr==false){
            throw new NotFoundHttpException('该通话记录不存在');
        }
        $cdr['record'] = '/var/spool/asterisk/monitor/'.decryptPhone('aes', urldecode($cdr['record']));
        if ($cdr['record'] && is_file($cdr['record'])){
            $filenamedis = date('Y-m-d-H-i-s') . strrchr($cdr['record'], '.');
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Content-Disposition: attachment; filename = " . $filenamedis);
            header("Content-Length: " . filesize($cdr['record']));
            header("Content-Type: application/octet-stream");
            return file_get_contents($cdr['record']);
        }
        throw new NotFoundHttpException('录音文件不存在');
    }

    /**
     * 播放录音
     * @param $uniqueid
     * @throws NotFoundHttpException
     */
    public function actionPlay($uniqueid)
    {
        $cdr = (new Query())->from('dgg_cdr')->where(['uniqueid'=>$uniqueid])->one();
        if ($cdr==false){
            throw new NotFoundHttpException('该通话记录不存在');
        }
        $cdr['record'] = '/var/spool/asterisk/monitor/'.decryptPhone('aes', urldecode($cdr['record']));
        if ($cdr['record'] && is_file($cdr['record'])){
            $path = $cdr['record'];
            $fileSize = filesize($path);
            $etag = md5(filemtime($path));
            $fp = fopen($path, 'rb');
            if (!$fp) {
                die('Could not open file');
            }
            $start = 0;
            $end = $fileSize - 1;
            if (isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])) {
                //获取请求头中的Range字段
                $range = explode('-', substr($_SERVER['HTTP_RANGE'], strlen('bytes=')));

                $start = $range[0];
                if ($range[1] > 0) {
                    $end = $range[1];
                }

                //构造断点续传响应头
                header('HTTP/1.1 206 Partial Content');
                header('Status: 206');
                header('Accept-Ranges: bytes');
                header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize);
                header('Content-Length: ' . ($end - $start + 1));
            } else {
                header('Content-Length: ' . $fileSize);
            }
            header('Content-Type: audio/mpeg');
            header('Last-Modified: ' . date('D, d M Y H:i:s \G\M\T', filemtime($path)));
            header('ETag: "' . $etag . '"');
            header('Expires: 0');
            if ($start > 0) {
                fseek($fp, $start); //移动文件指针
            }
            $bytesPosition = $start;
            while (!feof($fp) && $bytesPosition <= $end) {
                $chunk = 1024 * 1024 * 50; //每次读取50k
                if ($bytesPosition + $chunk > $end + 1) {
                    $chunk = $end - $bytesPosition + 1;
                }
                $chunk = fread($fp, $chunk);
                if (!$chunk) {
                    throw new NotFoundHttpException('无法读取文件');
                }
                print($chunk);
                flush();
                $bytesPosition += $chunk;
            }
            fclose($fp);
        }
        throw new NotFoundHttpException('录音文件不存在');
    }

}
